# -*- coding: utf-8 -*-
from PySide2 import QtWidgets
import maya.cmds as mc
import maya.mel as mel
import os, glob
import DH_PySideUidata
from DHAnimation import DH_setHeadsUpDisplay
reload (DH_setHeadsUpDisplay)

filepath = str(os.path.split(os.path.realpath(__file__))[0])
form_class, base_class = DH_PySideUidata.loadUiType(filepath+'/set_playBlast.ui')

class loadselectUI(base_class, form_class):
    # file type dict
    file_type_dict = {
        'qt':'.mov',
        'avi':'.avi'
    }

    def __init__(self):
        self.window_name = 'set_playBlast_window'
        if mc.window(self.window_name, exists=True):
            mc.deleteUI(self.window_name)
        super(loadselectUI, self).__init__(parent=DH_PySideUidata.getMayaWindow())
        self.setupUi(self)
        desktop = QtWidgets.QApplication.desktop().availableGeometry()
        size = self.geometry()
        self.move((desktop.width()-size.width())/2, (desktop.height()-size.height())/2)
        self.set_file_path()
        self.set_frame_range()
        self.listAllCams()
        self.pushButton_3.clicked.connect(self.reset_file_path)
        self.pushButton_2.clicked.connect(self.dialog_to_file_path)
        self.pushButton_4.clicked.connect(self.set_frame_range)
        self.pushButton.clicked.connect(self.play_blast_apply)
        self.pushButton_5.clicked.connect(self.deleteHUD)
        self.pushButton_6.clicked.connect(self.showHUD)
        self.selectProjectMenu.currentTextChanged.connect(self.selectProject)
        self.set_Project()
        self.selectProject()
        
    def showHUD(self):
        if mc.objExists('playBlastNode'):
            mc.delete('playBlastNode')          
        modelCameraName = ''
        modelCameraNameTemp = mc.getPanel(withFocus=True)        
        if (modelCameraNameTemp != 'outlinerPanel1') and (modelCameraNameTemp != 'graphEditor1'):
            modelCameraName = modelCameraNameTemp
        if not mc.getPanel(typeOf=modelCameraName)=='modelPanel':
            mc.warning('ѽ�����һ����ͼ�������Ȼ�Ҳ�֪�����ĸ�~')
            return  
        mc.loadPlugin( "Y:/OldFile/X_Projects/DHTool/mll/HUD_5.mll" )
        mc.file("Y:/OldFile/X_Projects/DHTool/ma/HUDNodes.ma",type="mayaAscii",ignoreVersion=True,i = True)

        DH_setHeadsUpDisplay.setHeadsUpDisplay().applyHUD()
        self.set_HUD_pos()
        endTime = str(int(mc.playbackOptions(q=True, maxTime=True)))
        mc.expression(s="string $time = frame;string $endTime = `playbackOptions -q -maxTime`;\nsetAttr -type \"string\" Frame|testo.text ($time+\"/\"+$endTime);",o = 'Frame|testo',ae=1,uc=all,name = 'frameExp')

     
        
    def selectProject(self):
        whichProject = str(self.selectProjectMenu.currentText())
        #print whichProject
        if whichProject == 'Phoenix':
            self.spinBox_3.setValue(2048)
            self.spinBox_4.setValue (858)
            self.doubleSpinBox.setValue (1.00)
            self.comboBox_2.setCurrentIndex(0)
        elif whichProject == 'ZSZR':
            self.spinBox_3.setValue(2560)
            self.spinBox_4.setValue(1080)
            self.doubleSpinBox.setValue(1.00)
            self.comboBox_2.setCurrentIndex(0)
        elif whichProject == 'XCM':
            self.spinBox_3.setValue(1433)
            self.spinBox_4.setValue(600)
            self.doubleSpinBox.setValue(1.00)
            self.comboBox_2.setCurrentIndex(1)
             

        scriptDir = mc.internalVar(usd=True)
        aboutDir = os.path.abspath(os.path.join(os.path.dirname(scriptDir), os.path.pardir))
        filePath = open(unicode(aboutDir)+'/'+'whichProject'+unicode('.proj'), 'w')
        filePath.write(whichProject.encode('utf8'))
        filePath.close()         
        
        
    def listAllCams(self):
        self.selectCameraMenu.clear()
        allCamShapes = mc.ls(ca=True)
        mc.select(allCamShapes,r = True)
        mc.pickWalk(d='up')
        allCams=mc.ls(sl=True)
        #print allCams
        removeCams = {u"front",u"persp",u"side",u"top",u"left"} 
        '''
        for eachCam in removeCams:
            if mc.objExists(eachCam):
                allCams.remove(eachCam)
        '''
        #print allCams
        #camNum = len(allCams)
        #self.selectCameraMenu.setCurrentIndex(1)
        #self.selectCameraMenu.setCurrentText('hello')
        mc.select(cl=True)
        #print allCams
        self.selectCameraMenu.addItems(allCams)
        #self.selectCameraMenu.removeItem(0)
        #for i in range(0,camNum):
           # self.selectCameraMenu.setCurrentIndex(i)
            #self.selectCameraMenu.setCurrentText(allCams[i])
    def renameCam(self):
        ifChange = int(self.ifChangeCamNaButt.isChecked())
        modelCameraName = ''
        modelCameraNameTemp = mc.getPanel(withFocus=True)
        if  (modelCameraNameTemp != 'outlinerPanel1') and (modelCameraNameTemp != 'graphEditor1'):
            modelCameraName = modelCameraNameTemp
        cameraName = ''
        camNewName = ''
        if modelCameraName != '':
            cameraName = mc.modelEditor(modelCameraName, q=True, camera=True)
        if ifChange == 1:
            whichProject = str(self.selectProjectMenu.currentText())
            currentCam = str(self.selectCameraMenu.currentText())
            if cameraName != currentCam :
                #print('����ѡ�Զ��޸�������ƣ���Ҫ��ѡ����ȷ�������')
                return 0
            file_name = mc.file(q=True,sn=1,shn=1)
            whichShotTemp = file_name.split("_")
            if len(whichShotTemp)>=2:
                whichShot =   whichShotTemp[1]
            else:
                whichShot = whichShotTemp[0]
            startFrame = str(int(mc.playbackOptions(q=True, minTime=True)))+'f'
            endFrame = str(int(mc.playbackOptions(q=True, maxTime=True)))+'f'
            if whichProject == 'Phoenix':  
                camNewName = 'Cam_'+whichShot+'_'+startFrame+'_'+endFrame
                if mc.objExists(currentCam):
                    mc.rename(currentCam,camNewName)
                    currentCamString = 'CamName'+'|'+'testo'
                    mc.setAttr(currentCamString+'.text', camNewName,type = 'string')
            elif whichProject == 'XCM':
                camNewName = 'Cam_XCM_'+whichShot+'_'+startFrame+'_'+endFrame
                if mc.objExists(currentCam):
                    mc.rename(currentCam,camNewName)
                    currentCamString = 'CamName'+'|'+'testo'
                    mc.setAttr(currentCamString+'.text', camNewName,type = 'string')
            elif whichProject == 'ZSZR': 
                camNewName = 'CAM_E01SH007_'+whichShot

                if mc.objExists(currentCam):
                    mc.rename(currentCam,camNewName)
                    currentCamString = 'CamName'+'|'+'testo'
                    mc.setAttr(currentCamString+'.text', camNewName,type = 'string')
        self.listAllCams()
               
    def set_file_path(self):
        file_type = self.file_type_dict.get(self.comboBox.currentText())
        file_name = mc.file(q=True, sn=True)
        filePath = ''
        scriptDir = mc.internalVar(usd=True)
        aboutDir = os.path.abspath(os.path.join(os.path.dirname(scriptDir), os.path.pardir))
        fileList = glob.glob(aboutDir+'/*.path')
        if fileList:
            file_path = open(unicode(aboutDir)+'/'+'playblast'+unicode('.path'), 'r')
            filePathStr = file_path.read()
            filePath = os.path.dirname(filePathStr) +'/'+ os.path.basename(file_name)
            #print filePath
            file_path.close() 
        if filePath:
            self.lineEdit.setText(os.path.splitext(filePath)[0]+file_type)
        elif file_name:
            # �Զ�����Ϊmaya�ļ�ͬĿ¼��ͬ����Ƶ�ļ�
            self.lineEdit.setText(os.path.splitext(file_name)[0]+file_type)
        else:
            # ��ѯ��ʱĿ¼
            scriptDir = mc.internalVar(utd=True)
            # ������ʱĿ¼����Ƶ�ļ�����
            self.lineEdit.setText(scriptDir+'untitled'+file_type)
            
    def set_Project(self):
        scriptDir = mc.internalVar(usd=True)
        aboutDir = os.path.abspath(os.path.join(os.path.dirname(scriptDir), os.path.pardir))
        fileList = glob.glob(aboutDir+'/*.proj')
        filePathStr = ''
        if fileList:
            file_path = open(unicode(aboutDir)+'/'+'whichProject'+unicode('.proj'), 'r')
            filePathStr = file_path.read()
            #filePath = os.path.dirname(filePathStr) 
            #print filePathStr
            file_path.close()
            if filePathStr:
                self.selectProjectMenu.setCurrentText(filePathStr)
            
             
    def reset_file_path(self):
        file_type = self.file_type_dict.get(self.comboBox.currentText())
        file_name = mc.file(q=True, sn=True)
        if file_name:
            # �Զ�����Ϊmaya�ļ�ͬĿ¼��ͬ����Ƶ�ļ�
            self.lineEdit.setText(os.path.splitext(file_name)[0]+file_type)
        else:
            # ��ѯ��ʱĿ¼
            scriptDir = mc.internalVar(utd=True)
            # ������ʱĿ¼����Ƶ�ļ�����
            self.lineEdit.setText(scriptDir+'untitled'+file_type)


    def dialog_to_file_path(self):
        file_type = self.file_type_dict.get(self.comboBox.currentText())
        file_path = mc.fileDialog2(fileFilter='*'+file_type, dialogStyle=1) 
        if file_path:
            self.lineEdit.setText(file_path[0])
            scriptDir = mc.internalVar(usd=True)
            aboutDir = os.path.abspath(os.path.join(os.path.dirname(scriptDir), os.path.pardir))
            filePath = open(unicode(aboutDir)+'/'+'playblast'+unicode('.path'), 'w')
            filePath.write(file_path[0].encode('utf8'))
            filePath.close() 
    def deleteHUD(self):
        if mc.objExists('playBlastNode'):
            mc.delete('playBlastNode')
        if mc.objExists('frameExp*'):
            mc.delete('frameExp*')
    
    def set_HUD_pos(self):
        camName = DH_setHeadsUpDisplay.setHeadsUpDisplay().getCameraName()
        mc.setAttr(camName+'.displayResolution',0)
        mc.setAttr(camName+'.displayGateMask',0)
        mc.setAttr(camName+'.displaySafeAction',1)
        mc.setAttr(camName+'.displaySafeTitle',1)
        if mc.objExists('playBlastNode'):
            width = float(self.spinBox_3.value())
            height = float(self.spinBox_4.value())
            playBlastScale =  float(self.doubleSpinBox.value())
            ratioX = width/2048.0
            ratioY = height/858.0
            fontSize = 50 * ratioX*playBlastScale
            nodesList = {'Time','File','Animator','Size','FocalLength','CamName','fps','Frame'}
            for eachNode in nodesList:
                mc.setAttr(eachNode + "|"+".textFontSize",fontSize) 
                mc.setAttr(eachNode + "|"+".fontFaceName",0)
                currentPos0 = mc.getAttr(eachNode + "|"+".position0")
                currentPos1 = mc.getAttr(eachNode + "|"+".position1")
                mc.setAttr(eachNode + "|"+".position0", currentPos0*ratioX*playBlastScale)
                mc.setAttr(eachNode + "|"+".position1", currentPos1*ratioY*playBlastScale)
   
        
    def play_blast_apply(self):
         
        self.showHUD() 
                    
        self.set_frame_range() 
        ifchangeCamNa = self.renameCam()
        if ifchangeCamNa == 0:
            mc.warning('����ѡ�Զ�����������ƣ���Ҫ��ѡ����ȷ�����/��ͼ~��')
            return
          
        file_path = str(self.lineEdit.text())
        strart_frame = int(self.spinBox.value())
        end_frame = int(self.spinBox_2.value())
        format_name = str(self.comboBox.currentText())
        compression = str(self.comboBox_2.currentText())
        percent = int(self.doubleSpinBox.value()*100)
        width = int(self.spinBox_3.value())
        height = int(self.spinBox_4.value())

        if os.path.exists(file_path):
            if os.path.splitext(file_path)[0]!='%suntitled'%mc.internalVar(utd=True):
                confirm = mc.confirmDialog( title='Confirm', message='This file exists.\nReplace :" %s "?'%file_path, 
                    button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No')
                if confirm == 'Yes':
                    os.remove(file_path)
                else:
                    if mc.objExists('playBlastNode'):
                        mc.delete('playBlastNode') 
                        return
            else:
                os.remove(file_path)

        playbackSlider = mel.eval("$temp = $gPlayBackSlider")
        soundStr = mc.timeControl(playbackSlider,q=1,sound=1)
        mc.playblast(filename=file_path,sound = soundStr, format=format_name, compression=compression, 
                        percent=percent, widthHeight=[width, height], clearCache=True, 
                        quality=100, viewer=1, showOrnaments=1, fp=4, sequenceTime=0,
                        startTime=strart_frame, endTime=end_frame,offScreen=True)
        

    def set_frame_range(self):
        minVal = int(mc.playbackOptions(q=True, min=True))
        maxVal = int(mc.playbackOptions(q=True, max=True))
        self.spinBox.setValue(minVal)
        self.spinBox_2.setValue(maxVal)